package com.masterclient.app.modules.shop;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.alibaba.android.vlayout.layout.StaggeredGridLayoutHelper;
import com.alibaba.android.vlayout.layout.StickyLayoutHelper;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.commonbean.product.ProductMessage;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.FrozenDialog;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.shop.adapter.DividingLineLayoutAdapter;
import com.masterclient.app.modules.shop.adapter.ProductsLayoutAdapter;
import com.masterclient.app.modules.shop.adapter.StoreCouponLayoutAdapter;
import com.masterclient.app.modules.shop.adapter.StoreInfoLayoutAdapter;
import com.masterclient.app.modules.shop.adapter.StoreRecommendHorizontalLayoutAdapter;
import com.masterclient.app.modules.shop.adapter.StoreRecommendLayoutAdapter;
import com.masterclient.app.modules.shop.adapter.StoreSequenceLayoutAdapter;
import com.masterclient.app.modules.shop.beans.StoreBean;
import com.masterclient.app.modules.shop.beans.StoreRecommendBean;
import com.masterclient.app.modules.shop.beans.StoreRecommendGroupBean;
import com.masterclient.app.modules.shop.contract.StoreContract;
import com.masterclient.app.modules.shop.contract.StorePresenter;
import com.masterclient.app.modules.shop.interfacess.SellerBottomCallback;
import com.masterclient.app.modules.shop.interfacess.SellerInfoCallback;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @auther hjian
 * @date 2020/4/8.
 */
@Route(path = AroutePath.STORE_FRAGMENT)
public class StoreFragment extends BaseFragment<StorePresenter> implements StoreContract.View {

    @BindView(R.id.store_classify_recycler)
    RecyclerView storeRecycler;
    @BindView(R.id.store_classify_refresh)
    SmartRefreshLayout storeSwipeLayout;
    @BindView(R.id.search_icon)
    ImageView searchIcon;
    @BindView(R.id.search_hint)
    TextView searchHint;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.search_back)
    ImageView searchBack;
    @BindView(R.id.search_framelayout)
    FrameLayout searchFramelayout;
    @BindView(R.id.iv_back_top)
    ImageView ivBackTop;

    private String storeId,isDealer,isAgent;
    private int index;
    private boolean isStaggered = true;
    private List<DelegateAdapter.Adapter> adapters;
    private DelegateAdapter delegateAdapter;
    private StoreInfoLayoutAdapter storeInfoAdapter;
    private StoreCouponLayoutAdapter storeCouponLayoutAdapter;
    private StoreRecommendHorizontalLayoutAdapter storeSaleLayoutAdapter;
    private StoreRecommendLayoutAdapter storeRecommendLayoutAdapter;
    private DividingLineLayoutAdapter dividingLineLayoutAdapter;
    private StoreSequenceLayoutAdapter storeSequenceLayoutAdapter;
    private ProductsLayoutAdapter productsLayoutAdapter;
    private StickyLayoutHelper storeSequenceLayoutHelper;
    private LinearLayoutHelper linearLayoutProducts;
    private StaggeredGridLayoutHelper staggeredLayoutProducts;

    private boolean hasmore = true, isShowCommission = false;
    private int page;
    private String sequenceName;
    private SellerInfoCallback sellerInfoCallback;
    private SellerBottomCallback sellerBottomCallback;
    private VirtualLayoutManager layoutManager;

    public void setSellerInfoCallback(SellerInfoCallback sellerInfoCallback) {
        this.sellerInfoCallback = sellerInfoCallback;
    }

    public void setSellerBottomCallback(SellerBottomCallback sellerBottomCallback) {
        this.sellerBottomCallback = sellerBottomCallback;
    }

    public static StoreFragment getInstance(String store_id, String isDealer, String isAgent) {
        StoreFragment storeFragment = new StoreFragment();
        Bundle bundle = new Bundle();
        bundle.putString("store_id", store_id);
        bundle.putString("is_dealer", isDealer);
        bundle.putString("is_agent", isAgent);
        storeFragment.setArguments(bundle);
        return storeFragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_store, null);
    }


    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();
        ImmersionBar.with(this).statusBarDarkFont(true, 0.2f).fitsSystemWindows(false).init();
        searchFramelayout.setPadding(0, ImmersionBar.getStatusBarHeight(this), 0, 0);
        searchFramelayout.setBackgroundResource(R.color.transparent);

        storeId = getArguments().getString("store_id");
        isDealer = getArguments().getString("is_dealer");
        isAgent = getArguments().getString("is_agent");
        sequenceName = "hot";
        page = 1;
        index = 0;
        adapters = new LinkedList<>();

        layoutManager = new VirtualLayoutManager(mContext);
        storeRecycler.setLayoutManager(layoutManager);
        storeRecycler.setItemViewCacheSize(16);
        storeRecycler.setItemAnimator(null);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        for (int i = 0; i < 10; i++) {
            viewPool.setMaxRecycledViews(i, 10);
        }
        storeRecycler.setRecycledViewPool(viewPool);
        delegateAdapter = new DelegateAdapter(layoutManager, false);
        storeRecycler.setAdapter(delegateAdapter);



        storeRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int scrollY = 0;
                SparseIntArray mRecyclerItemHeight = new SparseIntArray();
                int first = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                View c = recyclerView.getLayoutManager().getChildAt(0); //this is the first visible row
                if (c != null) {
                    scrollY = -c.getTop();
                    mRecyclerItemHeight.put(first, c.getHeight());
                    for (int i = 0; i < first; ++i) {
                        scrollY += mRecyclerItemHeight.get(i); //add all heights of the views that are gone
                    }
                }

                float alph = 0f;
                if (scrollY >= ScreenUtils.dp2px(100) || first != 0){
                    alph = 1f;
                }else if (scrollY <= 7) {
                    alph = 0f;
                }else {
                    alph = scrollY * 1.0f / ScreenUtils.dp2px(100);
                }
                searchBg(alph);
                ivBackTop.setVisibility(alph>=1?View.VISIBLE:View.GONE);

            }
        });

        storeSwipeLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        ClassicsFooter footer = new ClassicsFooter(getActivity());
        footer.setTextSizeTitle(12);
        footer.setPadding(0,ScreenUtils.dp2px(5),0,ScreenUtils.dp2px(5));
        storeSwipeLayout.setRefreshFooter(footer);
        storeSwipeLayout.setEnableFooterTranslationContent(false);
        storeSwipeLayout.setEnableFooterFollowWhenNoMoreData(true);
        storeSwipeLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener(){
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                hasmore = true;
                refreshLayout.resetNoMoreData();
                sequenceName = "hot";
                if (storeSequenceLayoutAdapter != null){
                    storeSequenceLayoutAdapter.refresh();
                }
//                strsSale.clear();
                mPresenter.getSeller(storeId,page,sequenceName,isDealer,isAgent);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                page++;
                mPresenter.getSeller(storeId,page,sequenceName,isDealer,isAgent);
            }
        });


        mPresenter.getSeller(storeId,page,sequenceName,isDealer,isAgent);

    }

    private void searchBg(float alph){
        searchHint.setTextColor(alph > 0.3 ? 0xFF999FAA : 0xFFEDEFF2);
        searchBack.setImageResource(alph > 0.3 ? R.mipmap.back_black : R.mipmap.back_white);
        searchIcon.setImageResource(alph > 0.3 ? R.mipmap.icon_sousuo0 : R.mipmap.icon_sousuo);
        searchLl.setBackgroundResource(alph > 0.3 ? R.drawable.shape_store_search_bg_gray : R.drawable.shape_store_search_bg_white);
        searchFramelayout.setBackgroundColor(Color.argb((int) (255 * alph), 255, 255, 255));
    }


    @OnClick({R.id.search_ll, R.id.search_back, R.id.iv_back_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_ll:
                ARouter.getInstance().build(AroutePath.STORE_SEARCH_ACTIVITY).withBoolean("isSearch",true).withString("store_id",storeId).navigation();
                break;
            case R.id.search_back:
                getActivity().finish();
                break;
            case R.id.iv_back_top:
                searchBg(0);
                storeSwipeLayout.closeHeaderOrFooter();
                storeRecycler.scrollToPosition(0);
                ivBackTop.setVisibility(View.GONE);
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (storeSaleLayoutAdapter != null)
            storeSaleLayoutAdapter.removeTimer();
    }

    @Override
    public void getSellerResult(StoreBean dataBean) {
        hasmore = dataBean.isHas_more()&&dataBean.getProducts().size()>0;

        isDealer = dataBean.getIs_dealer();
        if (page == 1) {
//            adapters.clear();
//            delegateAdapter.setAdapters(adapters);
//            storeRecycler.setAdapter(delegateAdapter);
//            index = 0;
            isShowCommission = "1".equals(dataBean.getShow_commission());
            //店铺头消息
            sellerBottomCallback.onState(dataBean.getNavs() == null || dataBean.getNavs().size()<1);
            if("1".equals(isDealer)){
                dataBean.getDealer_info().setIs_dealer(true);
            }else {
                dataBean.getSeller().setIs_dealer(false);
            }
            sellerInfoCallback.onSellerInfo(dataBean.getIs_favorite(),dataBean.getOn_sale_title(),"1".equals(isDealer)?dataBean.getDealer_info():dataBean.getSeller());

            if ((!"1".equals(isDealer)&&(dataBean.getSeller() == null || TextUtils.isEmpty(dataBean.getSeller().getName())))
                    || ("1".equals(isDealer)&&(dataBean.getDealer_info() == null
                            || TextUtils.isEmpty(dataBean.getDealer_info().getName())))) {
                if (adapters.contains(storeInfoAdapter)) {
                    adapters.remove(storeInfoAdapter);
                    storeInfoAdapter = null;
                    index--;
                }
            }else {
                if (storeInfoAdapter == null) {
                    storeInfoAdapter = new StoreInfoLayoutAdapter(getActivity(), new SingleLayoutHelper(), 1, null, "1".equals(isDealer)?dataBean.getDealer_info():dataBean.getSeller(),
                            dataBean.getIs_favorite(), dataBean.getOn_sale_title(), new StoreInfoLayoutAdapter.OnInforCallback() {
                        @Override
                        public void favoriteClick(boolean isFavorite) {
                            if ("2".equals(Config.FROZEN)) {
                                FrozenDialog.showFrozen(mContext);
                                return;
                            }
                            if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {//判断是否已登录
                                startActivitryWithBundle(QuickLoginActivity.class, null);
                                return;
                            }
                            if (isFavorite) {
                                mPresenter.collectShop(storeId);
                            } else {
                                mPresenter.removeCollect(storeId);
                            }
                        }
                    });
                    adapters.add(storeInfoAdapter);
                    index++;
                }else{
                    storeInfoAdapter.refreshData("1".equals(isDealer)?dataBean.getDealer_info():dataBean.getSeller(),dataBean.getIs_favorite(), dataBean.getOn_sale_title());
                }
            }

//            List<StoreCouponBean> strs = new ArrayList<>();
//            strs.add(new StoreCouponBean());
//            for (int i = 0; i < (int)(4* Math.random())-1; i++) {
//                strs.add(new StoreCouponBean());
//            }

            //优惠券
            if (dataBean.getAvailable_coupon_group() == null || dataBean.getAvailable_coupon_group().size()<1) {
                if (adapters.contains(storeCouponLayoutAdapter)) {
                    adapters.remove(storeCouponLayoutAdapter);
                    storeCouponLayoutAdapter = null;
                    index--;
                }
            }else {
                if (storeCouponLayoutAdapter == null) {
                    storeCouponLayoutAdapter = new StoreCouponLayoutAdapter(getActivity(), new SingleLayoutHelper(),
                            1, null, dataBean.getAvailable_coupon_group(), new StoreCouponLayoutAdapter.ReceiveConponCallback() {
                        @Override
                        public void onReceiveConponCallback(String coupon_code) {
                            if (TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {//判断是否已登录
                                startActivitryWithBundle(QuickLoginActivity.class, null);
                                return;
                            }
                            mPresenter.pickUpSalesrule(coupon_code,"");
                        }
                    });
                    adapters.add(storeCouponLayoutAdapter);
                    index++;
                }else {
                    storeCouponLayoutAdapter.setData(dataBean.getAvailable_coupon_group());
                }
            }


            //今日特卖
            if (dataBean.getFast_buy_goods() == null || dataBean.getFast_buy_goods().getProducts() == null || dataBean.getFast_buy_goods().getProducts().size()<1) {
                if (adapters.contains(storeSaleLayoutAdapter)) {
                    adapters.remove(storeSaleLayoutAdapter);
                    storeSaleLayoutAdapter = null;
                    index--;
                }
            }else {
                if (storeSaleLayoutAdapter == null) {
                    storeSaleLayoutAdapter = new StoreRecommendHorizontalLayoutAdapter(getActivity(), new SingleLayoutHelper(), 1, null, againRecommendData(dataBean.getFast_buy_goods()));
                    adapters.add(storeSaleLayoutAdapter);
                    index++;
                }else {
                    storeSaleLayoutAdapter.setData(againRecommendData(dataBean.getFast_buy_goods()));
                }
            }


            //爆款推荐
            if (dataBean.getHot_recommend_group() == null || dataBean.getHot_recommend_group().getProducts() == null || dataBean.getHot_recommend_group().getProducts().size()<1) {
                if (adapters.contains(storeRecommendLayoutAdapter)) {
                    adapters.remove(storeRecommendLayoutAdapter);
                    storeRecommendLayoutAdapter = null;
                    index--;
                }
            }else {
                if (storeRecommendLayoutAdapter == null) {
                    storeRecommendLayoutAdapter = new StoreRecommendLayoutAdapter(getActivity(), new SingleLayoutHelper(), 1, null, againRecommendData(dataBean.getHot_recommend_group()));
                    adapters.add(storeRecommendLayoutAdapter);
                    index++;
                }else {
                    storeRecommendLayoutAdapter.setData(againRecommendData(dataBean.getHot_recommend_group()));
                }
            }

            //间隔线
            if (storeRecommendLayoutAdapter != null || (storeCouponLayoutAdapter == null
                    && storeRecommendLayoutAdapter == null && storeSaleLayoutAdapter == null)) {
                if (adapters.contains(dividingLineLayoutAdapter)) {
                    adapters.remove(dividingLineLayoutAdapter);
                    dividingLineLayoutAdapter = null;
                    index--;
                }
            }else {
                if (dividingLineLayoutAdapter == null) {
                    dividingLineLayoutAdapter = new DividingLineLayoutAdapter(getActivity(), new SingleLayoutHelper(), null, 1,ScreenUtils.dp2px(12));
                    adapters.add(dividingLineLayoutAdapter);
                    index++;
                }
            }

            //筛选排序
            if (dataBean.getProducts() == null || dataBean.getProducts().size()<1) {
                if (adapters.contains(storeSequenceLayoutAdapter)) {
                    adapters.remove(storeSequenceLayoutAdapter);
                    storeSequenceLayoutAdapter = null;
                    index--;
                }
            }else {
                if (storeSequenceLayoutAdapter == null) {
                    storeSequenceLayoutHelper = new StickyLayoutHelper();
                    searchFramelayout.measure(0, 0);
                    storeSequenceLayoutHelper.setOffset(searchFramelayout.getMeasuredHeight());
                    storeSequenceLayoutAdapter = new StoreSequenceLayoutAdapter(getActivity(), storeSequenceLayoutHelper, 1, isShowCommission,null, new StoreSequenceLayoutAdapter.SequenceClickListener() {
                        @Override
                        public void onSequenceClick(String sequenceName) {
                            StoreFragment.this.sequenceName = sequenceName;
                            page = 1;
                            hasmore = true;
                            storeSwipeLayout.resetNoMoreData();
                            mPresenter.getSeller(storeId,page,sequenceName,isDealer,isAgent);
                            storeSwipeLayout.closeHeaderOrFooter();
                            storeRecycler.scrollToPosition(index - 2);
                        }

                        @Override
                        public void onSwitchList(boolean isSwitchGrid) {
                            isStaggered = !isStaggered;
                            productsLayoutAdapter.setItemType(isStaggered);
                            delegateAdapter.setAdapters(adapters);
                            storeSwipeLayout.closeHeaderOrFooter();
                            storeRecycler.scrollToPosition(index-2);
                        }
                    });

                    adapters.add(storeSequenceLayoutAdapter);
                    index++;
                }
            }

            //商品列表

            if (dataBean.getProducts() == null || dataBean.getProducts().size()<1) {
                if (adapters.contains(productsLayoutAdapter)) {
                    adapters.remove(productsLayoutAdapter);
                    productsLayoutAdapter = null;
                    index--;
                }
            }else {
                if (productsLayoutAdapter == null) {
                    linearLayoutProducts = new LinearLayoutHelper();
                    linearLayoutProducts.setMargin(ScreenUtils.dp2px(12), ScreenUtils.dp2px(12)
                            , ScreenUtils.dp2px(12), ScreenUtils.dp2px(32));
                    linearLayoutProducts.setDividerHeight(ScreenUtils.dp2px(12));

                    staggeredLayoutProducts = new StaggeredGridLayoutHelper(2);
                    staggeredLayoutProducts.setHGap(ScreenUtils.dp2px(9));
                    staggeredLayoutProducts.setVGap(ScreenUtils.dp2px(9));
                    staggeredLayoutProducts.setMargin(ScreenUtils.dp2px(12), ScreenUtils.dp2px(12)
                            , ScreenUtils.dp2px(12), ScreenUtils.dp2px(32));

                    List<LayoutHelper> layoutHelpers = new ArrayList<>();
                    layoutHelpers.add(staggeredLayoutProducts);
                    layoutHelpers.add(linearLayoutProducts);
                    productsLayoutAdapter = new ProductsLayoutAdapter(getActivity(), layoutHelpers, null, againProductsData(dataBean.getProducts()));
                    productsLayoutAdapter.setStrings("店铺");
                    adapters.add(productsLayoutAdapter);
                    index++;
                }else {
                    productsLayoutAdapter.addData(againProductsData(dataBean.getProducts()), true);
                }
            }

            delegateAdapter.setAdapters(adapters);
        }else {
            productsLayoutAdapter.addData(againProductsData(dataBean.getProducts()), false);
        }

        storeSwipeLayout.finishRefresh();
        if (!hasmore || dataBean.getProducts() == null || dataBean.getProducts().size()<1) {
            if (productsLayoutAdapter != null) {
                storeSwipeLayout.finishLoadMoreWithNoMoreData();
            }else {
                storeSwipeLayout.setEnableLoadMore(false);
            }
        }else {
            storeSwipeLayout.finishLoadMore();
        }




    }

    @Override
    public void getSellerFailed(String msg) {
        showToast(msg);
        if (page>1){
            storeSwipeLayout.finishLoadMore(false);
        }else {
            storeSwipeLayout.finishRefresh(false);
        }
    }

    @Override
    public void collectSuccess(boolean isCollect) {
        storeInfoAdapter.setIsFavorite(isCollect?"1":"0");
        sellerInfoCallback.onSellerInfo(isCollect?"1":"0",null,null);
        showToast(isCollect?"关注成功":"已取消关注");
    }

    @Override
    public void pickUpSalesruleSuccess(String coupon_code, String msg) {
        storeCouponLayoutAdapter.refreshDataChanged();
        showToast(msg);
    }

    @Override
    public void pickUpSalesruleFailed(String msg) {
        showToast(msg);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden&&isVisible()){
            if (storeInfoAdapter != null){
                storeInfoAdapter.setIsFavorite((((StoreActivity)getActivity()).isFavorite));
            }
        }
    }

    private List<ProductMessage> againProductsData(List<ProductMessage> productMessages){
        if (!isShowCommission) {
            for (ProductMessage item : productMessages) {
                item.setCommission("0");
            }
        }
        return productMessages;
    }


    private StoreRecommendGroupBean againRecommendData(StoreRecommendGroupBean recommendGroupBean){
        if (!isShowCommission) {
            for (StoreRecommendBean item : recommendGroupBean.getProducts()) {
                item.setCommission("0");
            }
        }
        return recommendGroupBean;
    }

}
